package com.sorhis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sorhis.common.constant.Constants;
import com.sorhis.dto.SysRoleDTO;
import com.sorhis.dto.SysTenantDTO;
import com.sorhis.entity.SysMenu;
import com.sorhis.entity.SysRole;
import com.sorhis.entity.SysTenant;
import com.sorhis.mapper.SysTenantMapper;
import com.sorhis.service.ISysRoleService;
import com.sorhis.service.ISysTenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sorhis.utils.DozerUtil;
import com.sorhis.utils.Tools;
import com.sorhis.vo.SysMenuTreeVO;
import com.sorhis.vo.SysTenantTableVO;
import com.sorhis.vo.SysTenantTreeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xihao.ding
 * @since 2025-02-11
 */
@Service
@RequiredArgsConstructor
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {


    private final ISysRoleService sysRoleService;
    @Override
    public IPage findPageList(SysTenantDTO sysTenantDTO) {
        //先分页查询 顶级租户
        Page<SysTenant> page = new Page(sysTenantDTO.getPageNum(), sysTenantDTO.getPageSize());
        IPage<SysTenant> result = this.page(page ,
                new LambdaQueryWrapper<SysTenant>()
                        .eq(ObjectUtil.isNotNull( sysTenantDTO.getIuse() ) , SysTenant::getIuse , sysTenantDTO.getIuse())
                        .like(StrUtil.isNotBlank( sysTenantDTO.getContacts() ) , SysTenant::getContacts , sysTenantDTO.getContacts())
                        .like(StrUtil.isNotBlank( sysTenantDTO.getIphone() ) , SysTenant::getIphone , sysTenantDTO.getIphone())
                        .like(StrUtil.isNotBlank( sysTenantDTO.getName() ) , SysTenant::getName , sysTenantDTO.getName())
                        .orderByDesc(SysTenant::getCreateTime));
//        if(CollectionUtil.isEmpty(result.getRecords())){
//            return result;
//        }
        // 所有租户
        //List<SysTenant> allTenantsList = this.list();
        //DozerUtil这里不知道会不会因为数据量大而有性能问题
        //List<SysTenantTableVO> allTenantsVoList = DozerUtil.mapList(allTenantsList, SysTenantTableVO.class);
//        List<SysTenantTableVO> sysTenantTableVOList = DozerUtil.mapList(result.getRecords(), SysTenantTableVO.class);
//        for (SysTenantTableVO sysTenantTableVO : sysTenantTableVOList) {
//            sysTenantTableVO.setChildren(getChildrenMenus(sysTenantTableVO.getId() , allTenantsVoList));
//        }
//        Page<SysTenantTableVO> resultPage = new Page<>(sysTenantDTO.getPageNum(), sysTenantDTO.getPageSize());
//        resultPage.setRecords(sysTenantTableVOList);
//        resultPage.setTotal(result.getTotal());
//        resultPage.setCurrent(result.getCurrent());
//        resultPage.setSize(result.getSize());
//        resultPage.setPages(result.getPages());
        return result;
    }

    private List<SysTenantTableVO> getChildrenMenus(String parentId , List<SysTenantTableVO> allTenants) {
//        QueryWrapper<SysTenantTableVO> wrapper = new QueryWrapper<>();
//        wrapper.eq("parent_id", parentId);
//        List<SysTenantTableVO> children = this.list(wrapper);
//        for (SysTenantTableVO child : children) {
//            child.setChildren(getChildrenMenus(child.getId()));
//        }
        return    allTenants.stream()
                .filter(tenant -> parentId.equals(tenant.getParentId()))
                .peek(tenant -> tenant.setChildren(getChildrenMenus( tenant.getId(),allTenants)))
                .collect(Collectors.toList());
    }


    @Override
    @Transactional
    public Boolean saveOrUpateDomain(SysTenantDTO sysTenantDTO) {
        SysTenant sysTenant = new SysTenant();
        BeanUtil.copyProperties(sysTenantDTO , sysTenant);
        return this.saveOrUpdate(sysTenant);
    }

    @Override
    public Boolean del(String id) {
        LambdaUpdateWrapper<SysTenant> updateWrapper = new LambdaUpdateWrapper<>();
        Assert.notEmpty(id , "ID不能为空");
        updateWrapper.eq(SysTenant::getId , id);
        updateWrapper.set(SysTenant::getDeleted , 1);
        return this.update(updateWrapper);
    }

    @Override
    public List<SysTenantTreeVO> tree() {
        List<SysTenant> sysTenantList = this.list(new LambdaQueryWrapper<SysTenant>());
        List<SysTenantTreeVO> result = new ArrayList<>();
        for(SysTenant sysTenant : sysTenantList){
            SysTenantTreeVO sysTenantTreeVO = new SysTenantTreeVO();
            sysTenantTreeVO.setId(sysTenant.getId());
            sysTenantTreeVO.setDisabled(sysTenant.getIuse() != 1);
            sysTenantTreeVO.setName(sysTenant.getName());
            sysTenantTreeVO.setParentId(sysTenant.getParentId());
            result.add(sysTenantTreeVO);
        }
        return this.recursionForTree(result, Constants.DEFAULT_ID);
    }

    @Override
    public IPage roleTenantPage(SysRoleDTO sysRoleDTO) {
        return sysRoleService.findRoleAndTenantPageList(sysRoleDTO);
    }


    public List<SysTenantTreeVO> recursionForTree(List<SysTenantTreeVO> lists,
                                                String parentId) {
        List<SysTenantTreeVO> result = new ArrayList<>();
        for (SysTenantTreeVO sysTenantTreeVO : lists) {
            if (sysTenantTreeVO.getParentId().equals(parentId)) {
                List<SysTenantTreeVO> array = recursionForTree(lists, sysTenantTreeVO.getId());
                if (array.size() != 0) {
                    sysTenantTreeVO.setChildren(array);
                }
                result.add(sysTenantTreeVO);
            }
        }
        return result;
    }


}
